package cn.tnar.yunpark.puxd;

import cn.tnar.yunpark.util.Strings;
import cn.tnar.yunpark.util.Util;
import com.google.gson.stream.JsonReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.*;

/**
 * Created by tieh on 2016/11/3.
 */
public class SignatureChecker {
    private static final Logger log = LoggerFactory.getLogger(SignatureChecker.class);

    public static Map<String, String> sortMap(Map<String, String> map) {
        Map<String, String> sorted = new TreeMap<String, String>();
        if (map != null && map.size() > 0) {
            sorted.putAll(map);
        }
        return sorted;
    }

    public static String getSignContent(Map<String, String> sortedParams) {
        StringBuilder content = new StringBuilder();
        List<String> keys = new ArrayList<String>(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;
        for (String key : keys) {
            String value = sortedParams.get(key);
            if (Strings.areNotNullOrEmpty(key, value)) {
                content.append((index == 0 ? "" : "&"));
                content.append(key);
                content.append("=");
                content.append(value);
                index++;
            }
        }
        return content.toString();
    }

    public static boolean check(Map<String, String> reqParams, String pwd) {
        Map<String, String> sortedMap = sortMap(reqParams);
        String sign = sortedMap.remove("sign");
        String toSign = getSignContent(sortedMap) + "&reportPwd=" + pwd;
        return Util.md5(toSign).equals(sign);
    }

    public static String sign(String json, String signKey) {
        JsonReader reader = new JsonReader(new StringReader(json));
        try {
            HashMap<String, String> map = new HashMap<String, String>();
            reader.beginObject();
            while (reader.hasNext()) {
                String key = reader.nextName();
                String value = reader.nextString();
                map.put(key, value);
            }
            reader.endObject();

            Map<String, String> sorted = sortMap(map);
            String toSign = getSignContent(sorted);
            String toMd5 = toSign + "&charset=UTF-8&key=" + signKey;
            return Util.md5(toMd5);
        } catch (Exception e) {
            log.warn("Sign error", e);
            return "";
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
}
